package com.raymond.client.session;

import com.raymond.client.msg.MessageManages;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 窗口管理器
 * 是否考虑A连接请求，B连接响应的问题
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2022-10-27 14:43
 */
public class WindowManager {
    /**
     * 消息管理
     */
    private final ConcurrentHashMap<Integer, MessageManages> msgManager = new ConcurrentHashMap<>();

    private final Semaphore semaphore;

    public WindowManager(int maxWindow) {
        this.semaphore = new Semaphore(maxWindow);
    }


    public MessageManages put(int sequenceId, MessageManages messageManages) {
        try {
            semaphore.acquire();
        } catch (Exception e) {
            throw new RuntimeException("获取请求许可异常", e);
        }
        return msgManager.put(sequenceId, messageManages);
    }

    public MessageManages put(int sequenceId, MessageManages messageManages, long timeout) {
        try {
            if (!semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("获取请求许可超时, 超时时间" + timeout);
            }
        } catch (Exception e) {
            throw new RuntimeException("获取请求许可异常,超时时间" + timeout, e);
        }
        return msgManager.put(sequenceId, messageManages);
    }


    public MessageManages remove(int sequenceId) {
        MessageManages remove = msgManager.remove(sequenceId);
        if (remove != null) {
            semaphore.release();
        }
        return remove;
    }

    public int size() {
        return msgManager.size();
    }
}
